<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<%@taglib prefix="s" uri="/struts-tags"  %>
<%
	String operation = request.getParameter("operation");
%>
<%@ page import="com.starbaba.core.web.constant.WebConstants"%>
<%@ page import="com.starbaba.system.user.model.UserVO"%>
<!DOCTYPE html>
<html lang="en">
<head>
<%@ include file="/common/common-css.jsp"%>
<style>
.table>th {
	vertical-align: center;
	background-color: grey;
}
input[type="checkbox"] {
   font-size: 100px;
   vertical-align:middle;
   margin-top:-2px; 
   margin-left:2px;
   margin-bottom:1px;
}
.comment-d {
	border: 1px solid #b5b5b5;margin-bottom: 10px;padding-bottom: 10px;
}
</style>
</head>
<body class="no-skin">
	<div class="page-content">
		<div class="page-content-area">
			<div class="row">
				<div class="col-xs-12 col-sm-12 widget-container-col">
					<form class="form-horizontal" id="itemTopic-form"
						name="itemTopic-form" method="post" enctype="multipart/form-data">
					<div class="widget-box widget-color-blue">
						<div class="widget-header widget-header-small">
							<h6 class="widget-title lighter">
								<i class="ace-icon glyphicon glyphicon-th-list"></i>专题信息编辑
							</h6>
							<div class="widget-toolbar no-border">
								<a href="#" data-action="collapse"> <i
									class="ace-icon fa fa-chevron-up"></i>
								</a>
							</div>
						</div>

						<div class="widget-body">
							<div class="widget-main" style="padding-bottom: 30px;">
							
										<input type="hidden" name="id" id="id" placeholder=""
											class="col-xs-12 col-sm-6" value="${paramsMap.model.id}">
										<input type="hidden" name="source_ids" id="source_ids" placeholder=""
											class="col-xs-12 col-sm-6" value="${paramsMap.source_ids}">
										<input type="hidden" name="status" id="status" placeholder=""
											class="col-xs-12 col-sm-6" value="${paramsMap.model.status}">
										<input type="hidden" name="operator" value="<%=((UserVO) session.getAttribute(WebConstants.SESSION_ATTRIBUTE_USER)).getUsername() %>"/>
										
										<div>
										
											<div>
												<label for="from">专题名称</label><br> <input type="text" name="title" id="title" placeholder=""
													class="col-xs-12 col-sm-12" value="${paramsMap.model.title}">
											</div>
											
											<div>
												<label for="from">副专题名称</label><br> <input type="text" name="secondary_title" id="secondary_title" placeholder=""
													class="col-xs-12 col-sm-12" value="${paramsMap.model.secondary_title}">
											</div>
											
											<br>
											<div style="text-align: left">
												<label for="from">专题类型</label><br>
												<select class="form-control" name="type" id="type" value="${paramsMap.model.type}" 
														onchange="selectTopicType()">
													<option value="">请选择</option>
													<option value="1" <s:if test="paramsMap.model.type == 1">selected</s:if>>首页列表</option>
													<option value="2" <s:if test="paramsMap.model.type == 2">selected</s:if>>商品专题</option>
													<option value="3" <s:if test="paramsMap.model.type == 3">selected</s:if>>介绍专题</option>
													<option value="4" <s:if test="paramsMap.model.type == 4">selected</s:if>>双十二活动专题</option>
												</select>
											</div>
											
											<div>
												<label for="from">浏览次数</label><br> <input type="text" name="people_view_count" id="people_view_count" placeholder=""
													class="col-xs-12 col-sm-12" value="">
											</div>
											
											<br>
											<div id="div-description">
										   		<label for="from">专题描述</label><br>
										   		<textarea rows="3" cols="20" name="description" id="description"  class="col-xs-12 col-sm-12" >
										   			${paramsMap.model.description}
										   		</textarea>
											</div>	
											
											<br>
											<div style="text-align: left" id="div-img">
												<label for="from">专题主图</label><br> <img id="img"
													name="img" src="${paramsMap.model.img}"
													onerror="javascript:this.src='http://img.xmiles.cn/img/void.png'"
													style="height: 100px;" />
											</div>
											<br>
											<div style="text-align: left" id="div-img_file">
												<input type="file" name="img_file" class="discovery-input-file" id="img_file"
													value="${img}" />
											</div>
											
											<br>
											<div style="text-align: left" id="div-small_img">
												<label for="from">推荐小图</label><br> <img id="small_img"
													name="small_img" src="${paramsMap.model.small_img}"
													onerror="javascript:this.src='http://img.xmiles.cn/img/void.png'"
													style="height: 100px;" />
											</div>
											<br>
											<div style="text-align: left" id="div-small_img_file">
												<input type="file" name="small_img_file" class="discovery-input-file" id="small_img_file"
													value="${small_img}" />
											</div>
										
										</div>
								
								</div>
							</div>
							
						</div>
					</form>
				</div>
				
			</div>
			
			<br>
			<br>
			<div>
				<label for="from">商品列表</label>
				<input type="button" name="btn_add" class="btn  btn-success  no-border" id="btn_add" 
					onclick="addItems()" value="新增"/>
			</div>
			
			<div class="row">
				<div class="col-xs-12">
						<table id="jquery-table" class="table table-striped table-bordered table-hover">
						</table>
				</div>
			</div>
			
			<br>
			<br>
			<div class="col-md-12 center">
				   <div class="col-md-offset-3 col-md-9" center>
					<button class="btn  btn-inverse  no-border " onclick="doCancel()">
						<i class="ace-icon fa fa-undo bigger-160"></i> 取消
					</button>
					&nbsp; &nbsp; &nbsp;
					<button id="btn-save" name="btn-save"
						class="btn  btn-success  no-border" type="button"
						onclick="doSave()">
						<i class="ace-icon fa fa-floppy-o bigger-160"></i> 保存
					</button>
				</div>
			</div>
			
		</div>
		
	<%@ include file="/common/common-js.jsp"%>
	<%@ include file="/discovery/maxlength.jsp"%>
	<script type="text/javascript" src="${ctx}/ace/js/maxlength.js"></script>
	<script type="text/javascript" src="${ctx}/js/wangEditor-1.3.11.min.js"></script>
	<script type="text/javascript" src="${ctx}/js/jquery.form.js"></script>
	<script type="text/javascript" src="${ctx}/js/call_func.js"></script>
	<script>
		
	function query_any(topic_id, source_ids){
	 	$("#output").removeAttr("style");
		//if(jqTable != null){
		//	jqTable.fnDraw();
		//} else {
		//	loaddata(topic_id, source_ids);
		//}
		
		 loaddata(topic_id, source_ids);
		 $("#delete_btn").attr("style","display:block");
		 $("#delete_hr").attr("style","margin-top:0px;margin-bottom:20px;display:block");
	 };
	
	 var jqTable = null;
	 var loaddata = function(topic_id, source_ids){
		jQuery(function($) {
			jqTable = $('#jquery-table').dataTable( {
			    //数据列控制（包括对应返回JSON属性名称，对应表头列索引位置、数据转换封装等）
			    "columnDefs": [
					{	  
						  "title":'置顶',
						  "targets": [0],
						  "data": "",   //JSON返回属性
						  "bSortable": false,
						  "width": "5%",
						  "render": function(value, type, row) { // 返回自定义内容
							  return '<i class="glyphicon glyphiconfir glyphicon-chevron-up" id="topProduct"  data-tabindex="'+row.id+'"></i>';
						  } 
					},
			    	{	  
						  "title":'排序',
						  "targets": [1],
						  "data": "",   //JSON返回属性
						  "bSortable": false,
						  "width": "5%",
						  "render": function(value, type, row) { // 返回自定义内容
							  return '<i class="glyphicon glyphiconfir glyphicon-chevron-up" id="upProduct" data-tabindex="'+row.id+'"></i><br><i class="glyphicon glyphicon-chevron-down" id="downProduct"></i>';
						  } 
					},
					{	  
						  "title":'商品ID',
						  "name":"item_source_id",
						  "data": "item_source_id",
						  "targets": [2],
						  "class": "center",
						  "bSortable": false,
						  "width": "1%",
					},
					{	  
						  "title":'商品标题',
						  "name":"item_title",
						  "data": "item_title",
						  "targets": [3],
						  "class": "center",
						  "bSortable": false,
						  "width": "1%",
					},
					{	  
						  "title":'状态',
						  "name":"item_status",
						  "data": "item_status",
						  "targets": [4],
						  "class": "center",
						  "bSortable": false,
						  "width": "1%",
						  "render": function(value, type, row) {
						  	    switch(value){
								case 1:return "上线";
								case 0:return "下线";
								default : return "";
							} 	
					      }
					},
					{	  
						  "title":'商品类型',
						  "name":"is_coupon_item",
						  "data": "is_coupon_item",
						  "targets": [5],
						  "class": "center",
						  "bSortable": false,
						  "width": "1%",
						  "render": function(value, type, row) {
						  	    switch(value){
								case 1:return "领券商品";
								case 0:return "返利商品";
								default : return "-";
							} 	
					      }
					},
					{	  
						  "title":'位置',
						  "name":"sort_index",
						  "data": "sort_index",
						  "targets": [6],
						  "class": "center",
						  "bSortable": false,
						  "width": "1%"
					},
					{	  
						  "title":'操作',
						  "name":"operation",
						  "data": "operation",
						  "targets": [7],
						  "class": "center",
						  "bSortable": false,
						  "width": "1%",
						  "render": function(value, type, row) {
						  		var temp =  "<input class='btn btn-success btn-sm' type='button' name='btn-remove' value='删除' onclick='deleteItem("+ row.item_source_id +")'/>&nbsp;&nbsp;&nbsp;&nbsp;";
	                         	return temp;
					    	 }
					},
			  	],
				"sAjaxSource": ctx+"/mallTopic/getTopicItemList.action?rand=" + Math.random() + "&topic_id=" + topic_id + "&source_ids=" + source_ids,
				"fnServerData": function ( sSource, aoData, fnCallback ) {//从服务器请求数据
			   			var data = $('#queryForm').serializeObject();
						
						data.aoData = JSON.stringify(aoData);
						$.ajax({
							"type": "POST",
							"dataType": 'json',
							"url": sSource,
							"data":data,
							"timeout":300000,
							"beforeSend": function() {
								// 显示loading
								//showLoading();
							},
							"success": function(resp){
								console.info(resp);
								//hideLoading();
								fnCallback(resp);
								initListPage();
								
							},		
							"error": function(XMLHttpRequest, textStatus, errorThrown) {
								alert('请求服务器错误,请刷新重试！！');//错误提示，包括服务器重启导致的session失效
							},			
							"complete": function () {
								//hideLoading();
							}
					});
				},
				"sScrollXInner": "100%",
				"sScrollY": "100%",//如果不设置，IE会有问题
			    "aaSorting": [[2,"desc"]], //初始化加载，默认按第几列排序、排序方式（列从0开始计算）
			    "destroy":true
			});
			
		});
	}
	
	
	$(function() {
			$('#img_file').change(function() {
				var file = this.files[0];
				var r = new FileReader();
				r.readAsDataURL(file);
				$(r).load(function() {
					$('#img').attr('src', this.result);
					$('#img_file').attr("value", this.result);
				});
			});
			
			$('#small_img_file').change(function() {
				var file = this.files[0];
				var r = new FileReader();
				r.readAsDataURL(file);
				$(r).load(function() {
					$('#small_img').attr('src', this.result);
					$('#small_img_file').attr("value", this.result);
				});
			});
		
		});
	
	
	$(document).ready(function() {
		
		//加载页面的时候，专题类型为首页列表时，隐藏：描述、专题主题、推荐小图
		selectTopicType();
		
	    //如果当前页面专题id不为空，说明是编辑操作，加载该专题下已添加的商品
		var topic_id = $("#id").val();
		if(topic_id != ''){
			query_any(topic_id,'');
		}
		
		//商品上移
        $('#jquery-table').delegate('#upProduct','click',function(){
			var arr = new Array();
			var thispos=$(this).parent('td').parent('tr');
			var thishtml=thispos.clone();
			var prevpos=$(this).parent('td').parent('tr').prev();
			var thisindex = thispos.index();
			if(thisindex==0){
				$('.discovery-up').show();
				setTimeout("$('.discovery-up').hide()",3000);
			}else{
				thispos.remove();
				prevpos.before(thishtml);
				
				$("#jquery-table tr td:nth-child(3)").each(function () {
        			arr.push($(this).text());
				});
				
				var arrstring = arr.join("#");
				$("#source_ids").val(arr.join(","));
				var topic_id = $("#id").val();
				
				 $.ajax({
					url: ctx+'/mallItemTopic/sortTab.action',
					type: 'POST',
					dataType: 'json',
					data: {"prdSortList": arrstring,"topic_id":topic_id},
					success:function(data){
                        if(topic_id != ''){
					 		query_any(topic_id,'');
						}
					},
					error:function(){
						console.log('排序失败');
					}
				});
			  }
			});
			
	        //商品下移
			$('#jquery-table').delegate('#downProduct','click',function(){
				var arr = new Array();
				var thispos=$(this).parent('td').parent('tr');
				var thishtml=thispos.clone();
				var nextpos=$(this).parent('td').parent('tr').next();
				var thisindex = thispos.index();
				if(thisindex==$("#jquery-table tbody tr").length - 1){
					$('.discovery-down').show();
					setTimeout("$('.discovery-down').hide()",3000);
				}else{
					thispos.remove();
			        nextpos.after(thishtml);
					
					$("#jquery-table tr td:nth-child(3)").each(function () {
        				arr.push($(this).text());
					});
					var arrstring = arr.join("#");
					$("#source_ids").val(arr.join(","));
					 $.ajax({
						url: ctx+'/mallItemTopic/sortTab.action',
						type: 'POST',
						dataType: 'json',
						data: {'prdSortList': arrstring,"topic_id":topic_id},
						success:function(data){
							if(topic_id != ''){
						 		query_any(topic_id,'');
							}
						},
						error:function(){
							console.log('排序失败');
						}
					}); 
					
				}
			}); 
			
			
			
		//商品置顶
        $('#jquery-table').delegate('#topProduct','click',function(){
        
        	var arr = new Array();
			var thispos=$(this).parent('td').parent('tr');
			var thishtml=thispos.clone();
			var thisindex = thispos.index();
        	
			if(thisindex==0){
				$('.discovery-up').show();
				setTimeout("$('.discovery-up').hide()",3000);
			}else{
				
				thispos.remove();
				$('#jquery-table').prepend(thishtml); 
				$("#jquery-table tr td:nth-child(3)").each(function () {
        			arr.push($(this).text());
				});
				
				var arrstring = arr.join("#");
				$("#source_ids").val(arr.join(","));
				var topic_id = $("#id").val();
				
				 $.ajax({
					url: ctx+'/mallItemTopic/sortTab.action',
					type: 'POST',
					dataType: 'json',
					data: {"prdSortList": arrstring,"topic_id":topic_id},
					success:function(data){
                        if(topic_id != ''){
					 		query_any(topic_id,'');
						}
					},
					error:function(){
						console.log('排序失败');
					}
				});
			  }
			});
			
		$("#output").hide();
	});
	
	//专题类型为首页列表时，隐藏：描述、专题主题、推荐小图
	function selectTopicType(){
		var type = $("#type").val(); 
		if(type == 1){
			$("#div-description").hide();
    		$("#div-img").hide();
    		$("#div-img_file").hide();
    		$("#div-small_img").hide();
    		$("#div-small_img_file").hide();
		}else{
			$("#div-description").show();
    		$("#div-img").show();
    		$("#div-img_file").show();
    		$("#div-small_img").show();
    		$("#div-small_img_file").show();
		}
	}
		
		//保存专题信息
		function doSave() {
			if ($.isBlank($("#title").val())) {
				parent.bootbox.alert("专题名称不能为空!");
				return;
			}
			
			if ($.isBlank($("#type").val())) {
				parent.bootbox.alert("专题名称不能为空!");
				return;
			}
			
			//获取选择商品的id
			var source_ids = $("#source_ids").val();
			
			var saveUrl = ctx + "/mallTopic/saveTopic.action?source_ids=" + source_ids;
			var options = {
				url : saveUrl,
				type : "POST",
				dataType : "json",
				beforeSend : function() {
					$(".load_bg,.load_img").show();
				},
				success : function(data) {
					alert(data['result']);
					parent.parent['__extdialog_active'].dialog('close');
					//parent.query_any();
				},
				error : function(XMLHttpRequest, textStatus, errorThrown) {
					alert("保存失败");
				},
				complete : function() {
					$(".load_bg,.load_img").hide();
				}
			};
			$('form[name="itemTopic-form"]').ajaxSubmit(options);
			
		}
		
	//移除商品，移除商品分两种：已入库，未入库
	function deleteItem(item_source_id){
	
		//移除已入库商品
		var topic_id = $("#id").val();
		var answer = window.confirm("是否确认删除?");
		if(answer){
			var data = {"item_source_id":item_source_id,"topic_id":topic_id};
			$.ajax({
				type:"post",	
				async:true,
				data:data,
				url: ctx + "/mallItemTopic/deleteTopicItem.action?rand=" + Math.random(),
				success:function(resp){
					alert("删除成功！");
					//query_any(topic_id, '');
					//删除商品后，清除文本框对应的source_id
					 var sourceIds = $("#source_ids").val();
					 sourceIds = sourceIds.replace(item_source_id, "");
					 $("#source_ids").val(sourceIds);
				},
				error:function(error){
					alert("删除失败！");
				}
				
			});
			
			//移除新勾选，但还没入库的商品（只需从页面移除）
			$("#jquery-table tr td:nth-child(2)").each(function (){
        		if(item_source_id == $(this).text()){
        		  $(this).parents("tr").remove();
        		}
			});
		}
			
	}
	
		//取消按钮
		function doCancel(){
			parent.parent['__extdialog_active'].dialog('close');
		}
		
		
		//打开添加商品页
		function addItems() {
			
 			var sourceIds = $("#source_ids").val();
 			
        	openDialogWithRand("/mallTopic/showProductPage.action?sourceIds=" + sourceIds,1000,1200,"商品列表",function (data){
        		
        		if(typeof(data) != "undefined"){
        			$("#source_ids").val(data);
        			query_any('', $("#source_ids").val());
        		}
		   });
   	    }

	</script>
</body>
</html>
